package com.alinesno.cloud.common.core.dubbo.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import com.alinesno.cloud.common.core.context.ApplicationContextProvider;
import com.alinesno.cloud.common.core.dubbo.BaseFilter;

/**
 * Dubbo服务拦截器，用于权限，调用日志等拦截，用于全局拦截
 * 
 * @author LuoAnDong
 * @since 2019年9月19日 上午7:23:53
 */
@Activate(group = { CommonConstants.CONSUMER }, order = -2000)
public class DubboTenantConsumerFilter extends BaseFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(DubboTenantConsumerFilter.class);

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

		Environment env = ApplicationContextProvider.getBean(Environment.class);
		log.debug("env:{}", env);

		// 添加参数
		if (env != null) {
			String applicationName = env.getProperty(DUBBO_APPLICATION_NAME); // 应用名称
			String applicationId = env.getProperty(DUBBO_APPLICATION_KEY_ID); // 应用 id
			String tenantId = env.getProperty(DUBBO_APPLICATION_TENANT_ID); // 租户id

			log.debug("consumer ======> application name:{} , application id:{} , tenant id:{}", applicationName , applicationId, tenantId);

			try {
				attachment(invoker, invocation)
						.setAttachment(APPLICATION_NAME, applicationName)
						.setAttachment(APPLICATION_ID, applicationId)
						.setAttachment(OPERATOR_ID, tenantId);
			} catch (Exception e) {
				log.error("dubbo参数设置异常:{}", e);
			}
		}

		Result result = invoker.invoke(invocation);
		return result;
	}

}
